<div id="root">
  <qf-table :data="tableData">
    <qf-table-column prop="id" label="编号1"></qf-table-column>
    <qf-table-column prop="id" label="编号2"></qf-table-column>
    <qf-table-column prop="name" label="姓名"></qf-table-column>
    <qf-table-column prop="age" label="年龄"></qf-table-column>
    <qf-table-column label="性别">
      <template slot-scope="item"> {{ item.sex == 1 ? '女' : '男' }} </template>
    </qf-table-column>
    <qf-table-column label="性别2">
      <template slot-scope="item"> {{ item.sex == 1 ? '女' : '男' }} </template>
    </qf-table-column>
  </qf-table>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  Vue.component("qfTableColumn", {
    // 将属性注入到模型中
    props: ["prop", "label"],
    template: `<span />`,
    // 组件渲染完毕后触发
    // 相当于window.onload
    mounted() {
      // console.log(this); // 组件实例/对象
      // console.log(this.$parent); // 父组件实例/对象（就是qfTable）

      this.$parent.column.push(this);
    },
  });

  Vue.component("qfTable", {
    data() {
      return {
        column: [
          // 之前：{title: '编号', key: 'id'}
          // 现在：{label: '编号', prop: 'id'}
          // 存放了一个个子组件对象， 然后每个字组件对象上有label、prop数据
        ],
      };
    },
    mounted() {
      // 父渲染 -> 渲染过程中解析子组件 子组件渲染 -> 子完毕后子mounted  -> .... -> 最后父mounted
      console.log(this.column);
      console.log(this.column[4].$scopedSlots.default({ sex: 1 })[0].text);
    },
    props: {
      data: {
        type: Array,
        default: [],
      },
    },
      template: `<table border="1" cellpadding="10" cellspacing="0">
        <thead>
        <tr>
          <th v-for="item in column">{{item.label}}</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="row in data">
          <!-- 
          <td>{{row.id}}</td>
          <td>{{row.name}}</td>
          <td>{{row.age}}</td>
          <td>暂不写</td>

          {{row.???}}
          {{row.col.prop}}
          {{row[col.prop]}}
          -->
          <td v-for="(col, index) in column">
            {{column[index].$scopedSlots.default ? column[index].$scopedSlots.default(row)[0].text : row[col.prop]}}
          </td>
        </tr>
        <!-- 默认插槽：因为调用了所以才提示组件不存在 -->
        <slot></slot>
        </tbody>
      </table>`,
    });
  const vm = new Vue({
    el: "#root",
    data: {
      tableData: [
        { id: 1, name: "张三", age: 3, sex: 1 },
        { id: 2, name: "赵四", age: 18, sex: 2 },
        { id: 3, name: "王五", age: 32, sex: 1 },
        { id: 4, name: "王五", age: 32, sex: 2 },
      ],
    },
    methods: {},
  });
</script>
